﻿

using eslib.tools.config;
using NLog;

namespace ArticleClientLib
{
    /// <summary>
    /// 代表一个软文根目录
    /// </summary>
    public class ArticleRootDir
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        void Info(string msg) => logger.Info(msg);
        void Error(string msg) => logger.Error(msg);

        /// <summary>
        /// 根目录
        /// </summary>
        public string Root { get; set; }

        public ArticleRootDir(string root)
        {
            Root = root;
            if (!Directory.Exists(Root)) Directory.CreateDirectory(Root);
        }

        /// <summary>
        /// 软文根目录下的分类集合（动态读取）
        /// </summary>
        public List<Classifly> Classiflies
        {
            get
            {
                List<Classifly> list = new();

                string[] dirs = Directory.GetDirectories(Root);
                foreach (var dir in dirs)
                {
                    //以目录名为分类id
                    try
                    {
                        string dirName = Path.GetFileName(dir);
                        long id = long.Parse(dirName);
                        list.Add(new Classifly(id, dir));
                    }
                    catch
                    {
                        throw new Exception($"分类目录只能以id为目录名称，{dir}");
                    }
                }
                return list;
            }
        }

        public Classifly? this[long classiflyId]
            => Classiflies.Where(c => c.classiflyId == classiflyId).FirstOrDefault();


        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        public (bool pass, string log) Check()
        {
            bool pass = true;
            string log = "";

            foreach (var cls in Classiflies)
            {
                var res = cls.Check();
                if (!res.pass)
                {
                    pass = false;
                    log += res.log + "\r\n";
                }
            }

            return (pass, log);
        }


        /// <summary>
        /// 创建目录，如果不存在
        /// </summary>
        /// <param name="classifly"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void CreateClassiflyIfNotExist(Classifly classifly)
        {
            ensureClassflyExist(classifly.classiflyId);
        }


        /// <summary>
        /// 确保目录存在
        /// </summary>
        /// <param name="id"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void EnsureClassflyExist(ClassiflyJson c)
        {
            ensureClassflyExist(c.id);

            //保存分类json
            string path = Path.Combine(Root, $"{c.id}");
            GenericJsonConfig.Save(c, Path.Combine(path, Classifly.JsonName));
        }


        void ensureClassflyExist(long id)
        {
            string path = Path.Combine(Root, $"{id}");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                Info($"创建目录{path}");

                this.Classiflies.Add(new Classifly(id, path));
            }
        }

    }
}
